package com.jwthhealth_pub.old.signutil.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.jwthhealth_pub.old.signutil.model.UserInfoModel;
import com.jwthhealth_pub.wristband.steps.bean.StepsDayModel;
import com.jwthhealth_pub.wristband.steps.bean.StepsTimeModel;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by liuzhen000 on 2016/5/30
 */
public class DbHelper extends OrmLiteSqliteOpenHelper {
    private static final String TABLE_NAME = "jwth.db";

    private static DbHelper instance;

    private Map<String, Dao> daos = new HashMap<String, Dao>();

    private DbHelper(Context context) {
        super(context, TABLE_NAME, null, 1);
    }

    public static synchronized DbHelper getHelper(Context context) {
        if (instance == null) {
            synchronized (DbHelper.class) {
                if (instance == null) {
                    instance = new DbHelper(context);
                }
            }
        }

        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, UserInfoModel.class);
            TableUtils.createTable(connectionSource, StepsTimeModel.class);  //每天24小时的运动情况
            TableUtils.createTable(connectionSource, StepsDayModel.class);  //每天的运动情况
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {

    }

    public synchronized Dao getDao(Class clazz) throws SQLException {
        Dao dao = null;
        String className = clazz.getSimpleName();

        if (daos.containsKey(className)) {
            dao = daos.get(className);
        }

        if (dao == null) {
            try {
                dao = super.getDao(clazz);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            daos.put(className, dao);
        }

        return dao;
    }

    /**
     * 释放资源
     */
    @Override
    public void close() {
        super.close();

        for (String key : daos.keySet()) {
            Dao dao = daos.get(key);
            dao = null;
        }
    }
}
